package com.xh3140.xwidget.recycler;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.AsyncDifferConfig;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

@SuppressWarnings("unused")
public abstract class BindingRecyclerAdapter<D> extends ListAdapter<D, BindingRecyclerAdapter.BindingViewHolder> {

  protected BindingRecyclerAdapter(@NonNull DiffUtil.ItemCallback<D> diffCallback) {
    super(diffCallback);
  }

  protected BindingRecyclerAdapter(@NonNull AsyncDifferConfig<D> config) {
    super(config);
  }

  @LayoutRes
  protected abstract int getItemBindingLayoutRes(int viewType);

  @NonNull
  @Override
  public BindingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    final ViewDataBinding binding = DataBindingUtil.inflate(inflater, getItemBindingLayoutRes(viewType), parent, false);
    return new BindingViewHolder(binding);
  }

  public static class BindingViewHolder extends RecyclerView.ViewHolder {
    private final ViewDataBinding mBinding;

    public BindingViewHolder(@NonNull ViewDataBinding binding) {
      super(binding.getRoot());
      mBinding = binding;
    }

    @SuppressWarnings("unchecked")
    @NonNull
    public final <B extends ViewDataBinding> B getBinding() {
      return (B) mBinding;
    }
  }
}
